package com.autonavi.yunda.yunji.controller;

import com.autonavi.yunda.yunji.common.exception.AmapPreconditions;
import com.autonavi.yunda.yunji.controller.request.EngineHealthCheckRequest;
import com.autonavi.yunda.yunji.core.enums.InterfaceStatus;
import com.autonavi.yunda.yunji.core.model.condition.HealthCheckLogQueryCondition;
import com.autonavi.yunda.yunji.core.model.dto.EngineHealthCheckDTO;
import com.autonavi.yunda.yunji.core.model.dto.HealthCheckLogDTO;
import com.autonavi.yunda.yunji.core.service.InterfaceConfigService;
import com.autonavi.yunda.yunji.core.vo.response.PageVO;
import com.autonavi.yunda.yunji.service.BucUserService;
import com.autonavi.yunda.yunji.service.EngineHealthCheckService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author cizhong.wcs
 * @date 2021/11/22 3:39 下午
 */
@RestController
public class HealthCheckController {
    @Resource
    EngineHealthCheckService engineHealthCheckService;
    @Resource
    BucUserService bucUserService;
    @Resource
    InterfaceConfigService interfaceConfigService;

    @RequestMapping(path = {"/actuator/health", "/health", "/tmd_status", "/status.taobao"})
    public String checkHealth() {
        return "success";
    }

    @PostMapping("health/save")
    public String add(@RequestBody @Validated EngineHealthCheckRequest request) throws Exception {
        String operator = bucUserService.getCurEmployeeIdOrNull();
        EngineHealthCheckDTO engineHealthCheckDTO;
        AmapPreconditions.checkArgumentForUser(InterfaceStatus.PUBLISHED.equals(interfaceConfigService.findByIdOrThrow(request.getInterfaceId()).getStatus()), "发布的接口才可以开启健康检查");
        if (null == request.getId()) {
            engineHealthCheckDTO = request.toAddDTO(operator);
            engineHealthCheckService.add(engineHealthCheckDTO);
        } else {
            engineHealthCheckDTO = request.toUpdateDTO(operator);
            engineHealthCheckService.update(engineHealthCheckDTO);
        }
        return "success";
    }

    @PostMapping("health/log/list")
    public PageVO<HealthCheckLogDTO> healthLogList(@RequestBody @Validated HealthCheckLogQueryCondition request) {
        return engineHealthCheckService.listHealthLog(request);
    }

    @GetMapping("health/findByInterfaceId")
    public List<EngineHealthCheckDTO> findByInterfaceId(Long interfaceId) {
        return engineHealthCheckService.findByInterfaceId(interfaceId);
    }
}
